<template>
  <div class="container-echart">
    <div :id="'echart' + timeId" class="interface-echart"></div>
  </div>
</template>
<script setup>
import * as echarts from "echarts";
import { getTotalNum } from "@/api/echarts";
import { onMounted, ref, watch, onBeforeUnmount, nextTick } from "vue";
const props = defineProps({
  title: {
    type: String,
  },
  propsData: {
    type: Object,
  },
  xDataArray: {
    // 柱形图x轴数据
    type: Array,
    default: function () {
      return ["1", "2", "3", "4", "5"];
    },
  },
  yDataArray: {
    //图标信息提示
    type: Array,
    default: function () {
      return [
        {
          name: "图例二",
          type: "category",
          label: {
            // 柱状图上的文字设置
            show: true, // 是否显示
            // fontSize:'500px',
            //   rotate: 60, // 文字旋转角度
            position: "top", // 显示位置
          },
          // barWidth: '50%', // 柱的宽度
          barGap: "5%", // 多个并排柱子设置柱子之间的间距
          data: [2, 2, 7, 5, 7, 4],
        },
        {
          name: "图例三",
          type: "category",
          label: {
            show: true, // 是否显示
            position: "top", // 显示位置
          },
          barGap: "5%", // 多个并排柱子设置柱子之间的间距
          data: [4, 2, 5, 8, 4, 2],
        },
      ];
    },
  },
});
// 饼图数据
const echartsData = ref();
let myEchart;
const timeId = ref(Math.floor(new Date().getTime() * Math.random())); // 使该图表保持唯id
const myEchartData = () => {
  let option = props.propsData;
  // { notMerge: true } 解决删除数据时,数据不刷新的问题
  myEchart.setOption(option, { notMerge: true });
};

watch(
  //监控数据变化
  () => props.xDataArray,
  () => {
    setTimeout(() => {
      myEchartData();
    }, 500);
  },
  { deep: true }
);
watch(
  //监控数据变化
  () => props.yDataArray,
  () => {
    setTimeout(() => {
      myEchartData();
    }, 500);
  },
  { deep: true }
);
onMounted(() => {
  getData();
  setTimeout(() => {
    const dom = document.getElementById(`echart${timeId.value}`);
    myEchart = echarts.init(dom);
    myEchartData();
  }, 500);

  // 当窗口发生变化时
  window.addEventListener("resize", () => {
    myEchart.resize();
  });
});
// 获取饼图数据
const getData = () => {
  getTotalNum().then((res) => {
    let data = res.data.data;
    let newData = [];
    // data.forEach(item => {
    //   newData.push({
    //     name: 'item'
    //   })
    // });
    for (const key in data) {
      newData.push({
        name: key,
        value: data[key],
      });
    }
    echartsData.value = newData;
  });
};
onBeforeUnmount(() => {
  window.removeEventListener("resize", () => {
    myEchart.resize();
  });
});
</script>
<style scoped lang="scss">
.container-echart {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.interface-echart {
  width: 100%;
  height: 400px;
}
</style>
